<template>
  <div class="department-management">
    <div class="page-header">
      <h2>部门管理</h2>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        新增部门
      </el-button>
    </div>
    
    <!-- 部门列表 -->
    <el-table :data="departments" v-loading="loading" stripe>
      <el-table-column prop="name" label="部门名称" width="200" />
      <el-table-column prop="description" label="部门描述" />
      <el-table-column label="人员数量" width="120">
        <template #default="{ row }">
          {{ getUserCount(row.id) }}
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editDepartment(row)">
            编辑
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="deleteDepartment(row)"
            :disabled="getUserCount(row.id) > 0"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 创建/编辑部门对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      :title="isEdit ? '编辑部门' : '新增部门'" 
      width="500px"
    >
      <el-form 
        :model="departmentForm" 
        :rules="departmentRules" 
        ref="departmentFormRef"
        label-width="80px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departmentForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        
        <el-form-item label="部门描述" prop="description">
          <el-input 
            v-model="departmentForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入部门描述" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="saveDepartment">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'

// 响应式数据
const departments = ref([])
const users = ref([])
const loading = ref(false)
const showCreateDialog = ref(false)
const isEdit = ref(false)
const currentDepartmentId = ref(null)

// 表单数据
const departmentForm = reactive({
  name: '',
  description: ''
})

// 表单验证规则
const departmentRules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' }
  ]
}

// 引用
const departmentFormRef = ref()

// 方法
const loadDepartments = async () => {
  loading.value = true
  try {
    const response = await api.get('/departments/')
    departments.value = response.data
  } catch (error) {
    ElMessage.error('加载部门列表失败')
  } finally {
    loading.value = false
  }
}

const loadUsers = async () => {
  try {
    const response = await api.get('/users/')
    users.value = response.data
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

const editDepartment = (department) => {
  isEdit.value = true
  currentDepartmentId.value = department.id
  Object.assign(departmentForm, {
    name: department.name,
    description: department.description || ''
  })
  showCreateDialog.value = true
}

const saveDepartment = async () => {
  if (!departmentFormRef.value) return
  
  await departmentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑部门
          await api.put(`/departments/${currentDepartmentId.value}`, departmentForm)
          ElMessage.success('部门更新成功')
        } else {
          // 创建部门
          await api.post('/departments/', departmentForm)
          ElMessage.success('部门创建成功')
        }
        
        showCreateDialog.value = false
        resetForm()
        loadDepartments()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新部门失败' : '创建部门失败')
      }
    }
  })
}

const deleteDepartment = async (department) => {
  const userCount = getUserCount(department.id)
  if (userCount > 0) {
    ElMessage.warning('该部门下还有用户，无法删除')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除部门 "${department.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/departments/${department.id}`)
    ElMessage.success('部门删除成功')
    loadDepartments()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除部门失败')
    }
  }
}

const resetForm = () => {
  Object.assign(departmentForm, {
    name: '',
    description: ''
  })
  isEdit.value = false
  currentDepartmentId.value = null
}

const getUserCount = (departmentId) => {
  return users.value.filter(user => user.department_id === departmentId).length
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  loadDepartments()
  loadUsers()
})
</script>

<style scoped>
.department-management {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}
</style>